package com.ylh.core;

import com.alibaba.fastjson.JSON;
import com.ylh.user.entity.UserDO;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;

import java.io.FileReader;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @ClassName InitData
 * @Description 初始化数据
 * @Author yanglh
 * @Date 2020/2/22 19:38
 */
@Component
public class InitData implements InitializingBean, DisposableBean {
    private List<UserDO> users = new CopyOnWriteArrayList<>();

    public List<UserDO> getUsers() {
        return users;
    }

    public void setUsers(List<UserDO> users) {
        this.users = users;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        URI uri = this.getClass().getResource("/users.json").toURI();
        byte[] data = Files.readAllBytes(Paths.get(uri));
        String fileStr = new String(data, StandardCharsets.UTF_8);
        System.out.println("initData初始化成功");
        users = JSON.parseArray(fileStr,UserDO.class);
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("initData被销毁了");
        URI uri = this.getClass().getResource("/users.json").toURI();
        String usersStr = JSON.toJSONString(this.users);
        Files.write(Paths.get(uri), usersStr.getBytes(StandardCharsets.UTF_8));
        System.out.println(usersStr);
    }
}
